#include "CommandMaker.h"
#include "../Settings/Settings.h"
#include "../Logger/Logger.h"

#include <string>
#include <sstream>
#include <stdlib.h>
#include <vector>

const char CommandMaker::separator_ = '$';



CommandMaker::CommandMaker(): commandStr_(""), playerNumber_(0), command_(NO),
                              playerName_(""), settings_(Settings::getInstance())
{
  commandTable_[CONNECT] = settings_.get("CONNECT_COMMAND");
  commandTable_[CONNECT_CONFIRM] = settings_.get("CONNECT_CONFIRM_COMMAND");
  commandTable_[START] = settings_.get("START_COMMAND");
  commandTable_[OPEN_CARD] = settings_.get("OPEN_CARD_COMMAND");
  commandTable_[GET_TOTEM] = settings_.get("GET_TOTEM_COMMAND");
  commandTable_[QUIT] = settings_.get("QUIT_COMMAND");
}




const std::string& CommandMaker::makeCommand()
{
  log("MAKE_COMMAND");
  
  commandStr_ = "";
  commandStr_ += separator_;
  

  std::map<Command, std::string>::iterator it = commandTable_.find(command_);
  if (it != commandTable_.end())
  {
    commandStr_ += it->second;
  }
  else
  {
    return commandStr_;
  }

  
  commandStr_ += separator_;
  
  std::stringstream stream;
  stream << playerNumber_;
  commandStr_ += stream.str();
  
  commandStr_ += separator_;
  

  stream.str("");
  stream << playerName_.size();
  commandStr_ += stream.str();
  
  commandStr_ += separator_;
  
  commandStr_ += playerName_;
  log("MAKE COMMAND ENDED");
  
  return commandStr_;
}


Command CommandMaker::getCommand()
{
  return command_;
}


void CommandMaker::setCommand(Command command)
{
  command_ = command;
}

int CommandMaker::getPlayerNumber()
{
  return playerNumber_;
}
 
void CommandMaker::setPlayerNumber(int playerNumber)
{
  playerNumber_ = playerNumber;
}

const std::string& CommandMaker::getPlayerName()
{
  return playerName_;
}

void CommandMaker::setPlayerName(const std::string &playerName)
{
  playerName_ = playerName;
}

void CommandMaker::setMaker(Command command, int playerNumber, const std::string &playerName)
{
  command_ = command;
  playerNumber_ = playerNumber;
  playerName_ = playerName;
}

const std::string& CommandMaker::makeStartCommand(const std::vector<Card>& cards)
{
  commandStr_ = "";
  commandStr_ += separator_;

  std::map<Command, std::string>::iterator it = commandTable_.find(START);
  if (it != commandTable_.end())
  {
    commandStr_ += it->second;
  }
  else
  {
    return commandStr_;
  }
  commandStr_ += separator_;
  std::stringstream stream;

  for (int i = 0; i != cards.size(); ++i)
  {
    stream.str("");
    stream << cards[i].getID();
    commandStr_ += stream.str();
    commandStr_ += separator_;

    stream.str("");
    stream << cards[i].getColor();
    commandStr_ += stream.str();
    commandStr_ += separator_;
  }
  return commandStr_;
}
